package com.goldenbean.listener;

import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.goldenbean.test.User;

public class RolePhase implements PhaseListener {

	public void afterPhase(PhaseEvent event) {
		// TODO Auto-generated method stub
	
		FacesContext fc = FacesContext.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
		
		String url = request.getRequestURI();
		
		if(url.toLowerCase().indexOf("login.jsf") < 0){
			HttpSession session = request.getSession(true);
			User user = (User) session.getAttribute("loginUser");
			if(user == null){
				
				
				FacesMessage msg = new FacesMessage();
				msg.setDetail("");
				msg.setSummary(url);
				msg.setSeverity(FacesMessage.SEVERITY_ERROR);
				FacesContext.getCurrentInstance().addMessage(null, msg);
				
				Application application = fc.getApplication();
				NavigationHandler nh = application.getNavigationHandler();
				nh.handleNavigation(fc, "", "nopower");
			}

		}
		
	
	}

	public void beforePhase(PhaseEvent event) {
		// TODO Auto-generated method stub
		
	}

	public PhaseId getPhaseId() {
		// TODO Auto-generated method stub
		return PhaseId.RESTORE_VIEW;
	}

}
